<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .btnBox {
      width: 262px;
      display: block;
      margin: 0 auto;
    }

    #nameBox {
      width: 735px;
      margin: 0 auto;
    }

    .nameButton {
      margin: 10px;
      width: 85px;
      height: 37px;
    }

    #name {
      text-align: center;
    }
  </style>
</head>

<body>
  <div class="btnBox">
    <input type="text" placeholder="请输入要添加的姓名" id="nameInput">
    <input type="button" value="添加" id="appendBtn">
    <input type="button" value="点名" id="randomName">
  </div>
  <div id="nameBox">
  </div>
  <h1 id="name"></h1>
  <script src="../WEB API/common.js"></script>
  <script>
    // 添加姓名
    id$("appendBtn").onclick = function () {
      var nameList = id$("nameInput").value;
      if (nameList) {
        var btnEle = document.createElement("button");
        btnEle.innerText = nameList;
        btnEle.className = "nameButton";
        id$("nameBox").appendChild(btnEle);
      }
      id$("nameInput").value = "";
    }

    // 判断姓名列表长度；随机选中次数，确认姓名
    id$("randomName").onclick = function () {
      var nameList = id$("nameBox").children;
      var order = Math.floor(Math.random() * (50 - 20)) + 20;
      if (nameList.length == 1) {
        alert("请输入大于或等于2个人的名字数量");
        return;
      } else if (nameList.length < 1) {
        alert("请添加名字");
        return;
      }
      clearInterval(this.timer);
      this.timer = setInterval(interval, 120);
      var timerNum = 0;
      function interval() {
        if (timerNum == order) {
          clearInterval(this.timer);
        } else {
          var nameListNum = nameList.length;
          var confirmName = Math.floor(Math.random() * (nameListNum - 0)) + 0;
          for (var j = 0; j < nameListNum; j++) {
            nameList[j].style.background = "";
          }
          nameList[confirmName].style.backgroundColor = "red";
          id$("name").innerText = nameList[confirmName].innerText;
          timerNum += 1;
        }
      }
    }
  </script>
</body>

</html>